﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.Common;
using System.Text;
using System.Windows.Forms;

namespace SP.OpenSource.CDC.Monitor
{
    public partial class BuildConnectionString : Form
    {
        String m_sConnectedConfigID = String.Empty;
        String m_sConnectionString = String.Empty;
        public String m_sDBServerName = String.Empty;
        public String m_sDBName = String.Empty;
        public bool m_bIntegratedSecurity = false;
        public String m_sUsername = String.Empty;
        public String m_sPassword = String.Empty;
        public String m_sProvider = String.Empty;
        public String m_sEncryptionType = String.Empty;

        public String sOleProvider = String.Empty;
        public String sDBSelection = String.Empty;
        public String sDefinedOleProviders = String.Empty;
        public String sDelimiter = String.Empty;
        public bool bDbProvider = false;

        public String sSchemaQuery = String.Empty;

        String m_sExePath = String.Empty;
        DataSet m_dsConfigurations = new DataSet();
        String m_sErrorMessage = String.Empty;
        String m_sGenericErrorMessage = "Exception raised while processing request." + Environment.NewLine + "Error Message: " ;
        String m_sFormTitle = "Build Connection String";
        public bool m_bCancel = true;

        public BuildConnectionString()
        {
            InitializeComponent();
        }
        public BuildConnectionString(String sMetaConnection, String sConnection,String sConnectedConfigID, String sDBSel, String sOleProviderSel,
                                     String sEncryptionType,String sOlePro, String sDelim, bool bProvider = false)
        {
            InitializeComponent();

            try
            {
                m_sConnectedConfigID = sConnectedConfigID;
                m_sConnectionString = sMetaConnection;
                m_sEncryptionType = sEncryptionType;

                LoadConnectionString(sConnection);

                if (false == bProvider)
                {
                    bDbProvider = bProvider;
                    
                }
                else
                {
                    bDbProvider = bProvider;
                    sOleProvider = sOlePro;
                    sDBSelection = sDBSel;
                    sDefinedOleProviders = sOleProviderSel;
                    sDelimiter = sDelim;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sGenericErrorMessage + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public BuildConnectionString(String sConnection, String sConnectedConfigID, bool bProvider = false)
        {
            InitializeComponent();

            try
            {
                m_sConnectedConfigID = sConnectedConfigID;

                LoadConnectionString(sConnection);

                if (false == bProvider)
                {
                    bDbProvider = bProvider;                    
                }
                else
                {
                    bDbProvider = bProvider;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sGenericErrorMessage + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public bool LoadConnectionString(String sConn)
        {
            try
            {
                if (sConn.Length > 0)
                {
                    String sIntegrartedSecurity = String.Empty;
                    String sErrorMessage = String.Empty;

                    BLL.Utils.ParseConnectionString(sConn, ref m_sDBServerName, ref m_sDBName,
                                                                             ref m_sProvider, ref sIntegrartedSecurity, ref m_sUsername,
                                                                             ref m_sPassword, ref sErrorMessage);

                    txtDBServer.Text = m_sDBServerName;

                    txtCDCDB.Text = m_sDBName;
                    if (sIntegrartedSecurity.ToUpper() == "TRUE")
                    {
                        m_bIntegratedSecurity = true;
                        chkIntegratedSecurity.Checked = true;
                        lblPassword.Visible = false;
                        lblUsername.Visible = false;
                        txtUsername.Visible = false;
                        txtPassword.Visible = false;
                    }
                    else
                    {
                        m_bIntegratedSecurity = false;
                        chkIntegratedSecurity.Checked = false;
                        lblPassword.Visible = true;
                        lblUsername.Visible = true;
                        txtUsername.Visible = true;
                        txtPassword.Visible = true;
                    }

                    txtUsername.Text = m_sUsername;
                    txtPassword.Text = m_sPassword;

                }

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sGenericErrorMessage + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        public void ResetUI()
        {
            txtDBServer.Text = String.Empty;
            txtCDCDB.Text = String.Empty;

            if (true == chkIntegratedSecurity.Checked)
                m_bIntegratedSecurity = true;
            else
                m_bIntegratedSecurity = false;


            txtUsername.Text = String.Empty;
            txtPassword.Text = String.Empty;
            txtDBServer.Text = String.Empty;
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            m_bCancel = true;
            ResetUI();
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                m_bCancel = false;
                m_sDBServerName = txtDBServer.Text;
                m_sDBName = txtCDCDB.Text;

                if (chkIntegratedSecurity.Checked == true)
                    m_bIntegratedSecurity = true;
                else
                    m_bIntegratedSecurity = false;

                m_sUsername = txtUsername.Text;
                m_sPassword = txtPassword.Text;

                //save data to file

                if (null != m_dsConfigurations || m_dsConfigurations.Tables[0].Rows.Count > 1)
                {
                    String sConn = "Data Source=" + txtDBServer.Text + ";";
                    sConn += "Initial Catalog=" + txtCDCDB.Text + ";";


                    if (true == chkIntegratedSecurity.Checked)
                        sConn += "Integrated Security=SSPI;";
                    else
                    {
                        sConn += "User ID=" + txtUsername.Text + ";";
                        sConn += "Password=" + String.Empty + ";";
                    }

                    //Encry pass
                    String sEncryPass = String.Empty;
                    if (txtUsername.Text.Length > 0)
                        BLL.Crypt.Encrypt(txtPassword.Text, m_sEncryptionType, ref sEncryPass, ref m_sErrorMessage);
                    else
                        sEncryPass = String.Empty;

                    foreach (DataRow drConfig in m_dsConfigurations.Tables[0].Rows)
                    {
                        if (drConfig["ConfigurationID"].ToString() == m_sConnectedConfigID)
                        {
                            drConfig["CDCStateConnectionString"] = sConn;
                            drConfig["CDCStateConnectionPassword"] = sEncryPass;

                        }
                    }
                    m_dsConfigurations.AcceptChanges();
                    m_dsConfigurations.WriteXml(m_sExePath + "\\Config\\Configuration.dat", XmlWriteMode.WriteSchema);

                }

                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sGenericErrorMessage + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            try
            {
                String sConn = "Data Source=" + txtDBServer.Text + ";";
                sConn += "Initial Catalog=" + txtCDCDB.Text + ";";


                if (true == chkIntegratedSecurity.Checked)
                    sConn += "Integrated Security=SSPI;";
                else
                {
                    sConn += "User ID=" + txtUsername.Text + ";";
                    sConn += "Password=" + txtPassword.Text + ";";
                }

                
                {
                    DbProviderFactory factory =
                        DbProviderFactories.GetFactory("System.Data.SqlClient");


                    DbConnection connection = factory.CreateConnection();
                    connection.ConnectionString = sConn;

                    connection.Open();
                    DataTable dtTest = connection.GetSchema("Tables");

                    connection.Close();
                }
                MessageBox.Show("Test connection completed successfully", "Build Connection String - Test Connection", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
            catch (Exception ex)
            {
                String sError = "There was an error while connecting to database.";
                sError += Environment.NewLine + Environment.NewLine;
                sError += ex.Message;

                MessageBox.Show(sError, "Build Connection String - Test Connection", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

       
        private void BuildConnectionString_Load(object sender, EventArgs e)
        {
            try
            {

                String sErrorMessage = String.Empty;
                //check if anything saved in config
                m_sExePath = System.Windows.Forms.Application.StartupPath.ToString();

                if (false == System.IO.File.Exists(m_sExePath + "\\Config\\Configuration.dat"))
                {
                    sErrorMessage = "File " + m_sExePath + "\\Config\\Configuration.dat" + " not found.";
                    sErrorMessage += Environment.NewLine;
                    sErrorMessage += " Make sure read/write permissions on the file.";
                    sErrorMessage += Environment.NewLine;
                    sErrorMessage += "If problem persists, please contact SecurePublish: support@securepublish.com";

                    MessageBox.Show(sErrorMessage, "Build Connection String - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return;
                }

                //Clean data table to avoid duplication.
                if (null != m_dsConfigurations && m_dsConfigurations.Tables.Count > 0 && m_dsConfigurations.Tables[0].Rows.Count > 0)
                    m_dsConfigurations.Tables.RemoveAt(0);

                m_dsConfigurations.ReadXml(m_sExePath + "\\Config\\Configuration.dat", XmlReadMode.ReadSchema);
                if (null != m_dsConfigurations || m_dsConfigurations.Tables[0].Rows.Count > 1)
                {
                    DataRow[] drConnectedSys = m_dsConfigurations.Tables[0].Select("ConfigurationID=" + m_sConnectedConfigID);

                    if (drConnectedSys.Length > 0)
                    {
                        if (drConnectedSys[0]["CDCStateConnectionString"].ToString().Length > 0)
                        {
                            String sServerName = String.Empty;
                            String sDBName = String.Empty;
                            String sProvider = String.Empty;
                            String sIntegrartedSecurity = String.Empty;
                            String sUsername = String.Empty;
                            String sPasword = String.Empty;

                            m_sErrorMessage = String.Empty;
                            BLL.Utils.ParseConnectionString(drConnectedSys[0]["CDCStateConnectionString"].ToString(), ref sServerName, ref sDBName,
                                               ref sProvider, ref sIntegrartedSecurity, ref sUsername, ref sPasword,
                                                 ref m_sErrorMessage);
                            if (sServerName.Length > 0 && sDBName.Length > 0)
                            {
                                txtDBServer.Text = sServerName;
                                txtCDCDB.Text = sDBName;
                            }
                            if (sIntegrartedSecurity.Length > 0 && sIntegrartedSecurity == "True")
                            {
                                txtUsername.Text = String.Empty;
                                txtPassword.Text = String.Empty;

                                chkIntegratedSecurity.Checked = true;
                                lblUsername.Visible = false;
                                lblPassword.Visible = false;
                                txtPassword.Visible = false;
                                txtUsername.Visible = false;
                            }
                            else
                            {
                                txtUsername.Text = sUsername;
                                //Decry password
                                String sPass = drConnectedSys[0]["CDCStateConnectionPassword"].ToString();
                                String sDePass = String.Empty;
                                BLL.Crypt.Decrypt(sPass, m_sEncryptionType, ref  sDePass, ref m_sErrorMessage);
                                
                                txtPassword.Text = sDePass;

                                chkIntegratedSecurity.Checked = false;
                                lblUsername.Visible = true;
                                lblPassword.Visible = true;
                                txtPassword.Visible = true;
                                txtUsername.Visible = true;
                            }

                        }

                        
                    }

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error while loading form. Error message: " + ex.Message, "Build Connection String - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void chkIntegratedSecurity_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (chkIntegratedSecurity.Checked == true)
                {
                    lblUsername.Visible = false;
                    lblPassword.Visible = false;
                    txtPassword.Visible = false;
                    txtUsername.Visible = false;
                }
                else
                {
                    lblUsername.Visible = true;
                    lblPassword.Visible = true;
                    txtPassword.Visible = true;
                    txtUsername.Visible = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(m_sGenericErrorMessage + ex.Message, m_sFormTitle + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }
}
